from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_protect,csrf_exempt
from django.core.context_processors import csrf 
from courses.models import Course,Request
from quiz.models import Lecture,Quiz,Grade
from registration.models import  User
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader

# list of mobile User Agents
mobile_uas = [
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda','xda-','iPad'
    ]
 
mobile_ua_hints = [ 'SymbianOS','Windows CE', 'Nokia', 'PSP', 'Opera Mini', 'iPhone', 'iPad', 'Android', 'Opera Mobi', 'webOS' ]
 
 
def mobileBrowser(request):
    ''' Super simple device detection, returns True for mobile devices '''
 
    mobile_browser = False
    ua = request.META['HTTP_USER_AGENT'].lower()[0:4]
 
    if (ua in mobile_uas):
        mobile_browser = True
    else:
        for hint in mobile_ua_hints:
            if request.META['HTTP_USER_AGENT'].find(hint) > 0:
                mobile_browser = True
 
    return mobile_browser
def delcourse(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    if user==course.teacher:
        course.delete()
    return HttpResponseRedirect('/courses/ITeach1')
@csrf_protect
def changename(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    Tmptitle= request.POST.get('value','Error in editing')
    print "this is" +Tmptitle
    course.title=Tmptitle
    course.save()
    url="/courses/mycourse/"+str(course_id)
    return HttpResponse()
@csrf_protect
def changelecturename(request,lecture_id):
    print "5ara"
    user=request.user
    print "after user"
    lecture=Lecture.objects.get(pk=lecture_id)
    print "lecture title" +lecture.title
    Tmptitle= request.POST.get('value','Error in editing')
    print "this is" +Tmptitle
    lecture.title=Tmptitle
    lecture.save()
    return HttpResponse()

def changeinfopage(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    return render_to_response('courses/editinfo.html',{'course' : course, 'user' : user})
@csrf_protect
def changeinfo(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    Tmptitle= request.POST.get('value','Error in editing')
    print "this is" +Tmptitle
    course.info=Tmptitle
    course.save()
    url="/courses/mycourse/"+str(course_id)
    return HttpResponse()
#    return HttpResponseRedirect(url)
def deletelecture(request,lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    if user==lecture.course.teacher:
        lecture.delete()
    url="/courses/"+str(lecture.course.id)+"/lectures/"
    return HttpResponseRedirect(url)

def confirmUnsubscribe(request,course_id):
     user=request.user
     course=Course.objects.get(pk=course_id)
     return render_to_response('quizs/confirmUnsub.html',{'user' : user,'course' :course})
def unsubscribe(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    course.Subscribers.remove(user)
    req=Request.objects.filter(course=course,sender=user,reciever=course.teacher)
    req.delete()
    return HttpResponseRedirect('/index1') 
def ITeach(request):
    user=request.user
    my_courses=Course.objects.filter(teacher=user)
    if mobileBrowser(request):
        return render_to_response('courses/m_ITeach.html',{'my_courses' : my_courses, 'user' : user})
    else:
        return render_to_response('courses/ITeach.html',{'my_courses' : my_courses, 'user' : user})
def ITeach1(request):
    user=request.user
    my_courses=Course.objects.filter(teacher=user)
    return render_to_response('courses/ITeach1.html',{'my_courses' : my_courses, 'user' : user})

def index1(request):
    user=request.user
    return render_to_response('index1.html',{'user' : user})

def index(request):
    user=request.user
   # if not user==AnonymousUser:
    #    courses=user.course_set.all()
    if mobileBrowser(request):
        return render_to_response('m_index.html',{'user' : user})
    else:
        return render_to_response('index.html',{'user' : user})

def listPerviousLectures(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    p=[]
    if user==course.teacher:
        lectures=Lecture.objects.filter(course=course)
    for lecture in lectures:
        if lecture.isStarted:
            if lecture.isEnded:
                p.append(lecture)
    if mobileBrowser(request):
        return render_to_response('courses/m_previous_lectures.html', context_instance=RequestContext(request,{'user' : user,'p':p, 'course': course}))
    else:
        return render_to_response('courses/previous_lectures.html', context_instance=RequestContext(request,{'user' : user,'p':p, 'course': course}))

def listsubPerviousLectures(request, course_id,user_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    sub=User.objects.get(pk=user_id)
    p=[]
    if user==course.teacher:
        lectures=Lecture.objects.filter(course=course)
    for lecture in lectures:
        if lecture.isStarted:
            if lecture.isEnded:
                p.append(lecture)
    return render_to_response('courses/subprevious_lectures.html', context_instance=RequestContext(request,{'user' : user,'sub': sub,'p':p, 'course': course}))

    
def viewLectures(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    p=[]
    r=[]
    u=[]
    if user==course.teacher:
        lectures=Lecture.objects.filter(course=course)
	for lecture in lectures:
		if lecture.isStarted:
			if lecture.isEnded:
				p.append(lecture)
			else:
				r.append(lecture)
		else:
			u.append(lecture)
    else:
        lectures=None
    if mobileBrowser(request):
        return render_to_response('courses/m_lectures.html',{'user' : user, 'lectures' : lectures,'p' : p, 'r' : r, 'u' : u})
    else:
        return render_to_response('courses/lectures.html',{'user' : user, 'lectures' : lectures,'course': course,'p' : p, 'r' : r, 'u' : u})


def CreateCourse(request):
    user=request.user
    if request.method== 'POST':
        Tmptitle= request.POST['title']
        Tmpinfo= request.POST['info']
        c=Course.objects.create(title=Tmptitle,info=Tmpinfo,teacher=user)
        c.save()
        return HttpResponseRedirect("/courses/ITeach")

        #return HttpResponseRedirect("/courses/mycourse/"+str(c.id))
    else:
        if mobileBrowser(request):
            return render_to_response('courses/m_create_course.html', context_instance=RequestContext(request,{'user' : user}))
        else:
            return render_to_response('courses/create_course.html', context_instance=RequestContext(request,{'user' : user}))


def stclasspage(request,course_id):
   user=request.user
   course=Course.objects.get(pk=course_id)
   if mobileBrowser(request):
        return render_to_response('quizs/m_stclasspage.html', context_instance=RequestContext(request,{'user' : user, 'course' : course}))
   else:
        return render_to_response('quizs/stclasspage.html', context_instance=RequestContext(request,{'user' : user, 'course' : course}))
def allinall(request,course_id):
   user=request.user
   course=Course.objects.get(pk=course_id)
   lectures=Lecture.objects.filter(course=course)
   RA=0
   WA=0
   quizs=[]
   for lecture in lectures:
       quizes=Quiz.objects.filter(lecture=lecture)
       for quiz in quizes:
           
           quizs.append(quiz)
           
           gr=Grade.objects.filter(quiz=quiz)
           for g in gr:
                if g.choice.isRight:
                    RA=RA+1
                else:
                    WA=WA+1
   if mobileBrowser(request):
       return render_to_response('quizs/m_allinall.html', context_instance=RequestContext(request,{'user' : user, 'course' : course, 'RA' : RA, 'WA' : WA, 'quizes' : quizs}))
   else:
       return render_to_response('quizs/allinall.html', context_instance=RequestContext(request,{'user' : user, 'course' : course, 'RA' : RA, 'WA' : WA, 'quizes' : quizs}))


def t_details(request,course_id):
   user=request.user
   course=Course.objects.get(pk=course_id)
   lectures=Lecture.objects.filter(course=course)
   RA=0
   WA=0
   quizs=[]
   for lecture in lectures:
       quizes=Quiz.objects.filter(lecture=lecture)
       for quiz in quizes:
           
           quizs.append(quiz)
           
           gr=Grade.objects.filter(quiz=quiz)
           for g in gr:
                if g.choice.isRight:
                    RA=RA+1
                else:
                    WA=WA+1
   
   if mobileBrowser(request):
    return render_to_response('courses/m_tcourse.html', context_instance=RequestContext(request,{'user' : user, 'course' : course})) 
   else:
    return render_to_response('courses/tcourse.html', context_instance=RequestContext(request,{'user' : user, 'course' : course, 'RA' : RA, 'WA' : WA, 'quizes' : quizs}))     
    
def subs_details(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    if mobileBrowser(request):
        return render_to_response('courses/m_subs_details.html',{'course' : course, 'user' : user})
    else:
        return render_to_response('courses/subs_details.html',{'course' : course, 'user' : user})

def subscribtionl(request,letter):
    user=request.user
    if letter=="sym":
        csess=Course.objects.all().exclude(teacher=user)
        cses=[]
        for cs in csess:
            if not cs.title[:1].isalpha():
               cses.append(cs) 
    else:
        cses=Course.objects.filter(title__startswith=letter).exclude(teacher=user).order_by('title')
    courses=[]
    for c in cses:
        tmp = c.Subscribers.all()

        if not tmp.__contains__(user):
            courses.append(c)
    
    if mobileBrowser(request):
        t = loader.get_template('courses/m_subscribtionl.html')
    else:
        t = loader.get_template('courses/subscribtionl.html')
 
    c = RequestContext(request, {'courses' : courses, 'user' : user}) # normally your page data would go here
 
    return HttpResponse(t.render(c))# Create your views here.
         

 #   return render_to_response('courses/subscribtionl.html',{'courses' : courses, 'user' : user})
    
def subscribtion(request):
    user=request.user
     
    if mobileBrowser(request):
        t = loader.get_template('courses/m_subscribtion.html')
    else:
        t = loader.get_template('courses/subscribtion.html')
 
    c = RequestContext(request, {'user' : user }) # normally your page data would go here
 
    return HttpResponse(t.render(c))# Create your views here.
    #return render_to_response('courses/subscribtion.html', {'user' : user})

def request(request,course_id):
    course=Course.objects.get(pk=course_id)
    user=request.user
    if not Request.objects.filter(course=course,sender=user,reciever=course.teacher).exists():
        r=Request(sender=user, reciever=course.teacher, course=course)
        r.save()
    else:
     r=None
    if mobileBrowser(request):
        return render_to_response('courses/m_request.html',{'req' : r, 'user' : user})
    else:
        return render_to_response('courses/request.html',{'req' : r, 'user' : user})

def requests(request):

    user=request.user
    requests=Request.objects.filter(reciever=user).exclude(accepted=True)
    if mobileBrowser(request):
        return render_to_response('courses/m_requests.html',{'requests' : requests, 'user' : user})
    else:
        return render_to_response('courses/requests.html',{'requests' : requests, 'user' : user})


def acceptreq(request,request_id):
    user=request.user
    r=Request.objects.get(pk=request_id)
    c=r.course
    c.Subscribers.add(r.sender)
    c.save()
    r.accepted=True
    r.save()
    if mobileBrowser(request):
        return render_to_response('courses/m_acceptreq.html',{'course' : c, 'req' : r, 'user' :user})
    else:
        return render_to_response('courses/acceptreq.html',{'course' : c, 'req' : r, 'user' :user})


def rejectreq(request,request_id):
    user=request.user
    r=Request.objects.get(pk=request_id)
    c=r.course

    r.accepted=True
    r.save()
    if mobileBrowser(request):
        return render_to_response('courses/m_rejectreq.html',{'course' : c, 'req' : r, 'user' : user})
    else:
        return render_to_response('courses/rejectreq.html',{'course' : c, 'req' : r, 'user' : user})
    
    
